<template>
  <div >
    <div v-for="spec in specs" :key="spec.key" class="sku-group">
      <div class="sku-title">{{ spec.key }}</div>
      <div class="sku-options">
        <div
            v-for="option in spec.values"
            :key="option"
            class="sku-option"
            :class="{
            'selected': selectedSpecs[spec.key] === option,
            'disabled': isOptionDisabled(spec.key, option)
          }"
            @click="selectSpec(spec.key, option)"
        >
          {{ option }}
        </div>
      </div>
    </div>
<!--    <div class="sku-info">-->
<!--      <span class="price">￥{{ currentPrice }}</span>-->
<!--      <span class="stock">库存: {{ currentStock }}</span>-->
<!--    </div>-->
  </div>
</template>

<script>
export default {
  name: 'SkuSelector',

  props: {
    skus: {
      type: Array,
      required: true,
      validator: function(skus) {
        return skus.every(sku =>
            'id' in sku &&
            'price' in sku &&
            'stock' in sku &&
            'spData' in sku
        )
      }
    }
  },

  data() {
    return {
      selectedSpecs: {} // 这个将在 mounted 钩子中被填充
    }
  },

  computed: {
    // 获取所有规格类型和其可能的值
    specs() {
      if (this.skus.length === 0) return [];

      const specMap = new Map();

      this.skus.forEach(sku => {
        const spData = JSON.parse(sku.spData);
        spData.forEach(spec => {
          if (!specMap.has(spec.key)) {
            specMap.set(spec.key, new Set());
          }
          specMap.get(spec.key).add(spec.value);
        });
      });

     let arr = Array.from(specMap).map(([key, values]) => ({
        key,
        values: Array.from(values)
      }));
      return arr;
    },

    // 当前选中SKU的价格
    currentPrice() {
      const selectedSku = this.getSelectedSku();
      return selectedSku ? selectedSku.price.toFixed(2) : '0.00';
    },

    // 当前选中SKU的库存
    currentStock() {
      const selectedSku = this.getSelectedSku();
      return selectedSku ? selectedSku.stock : 0;
    },

    // 检查是否所有规格都已选择
    isAllSelected() {
      return this.specs.every(spec => this.selectedSpecs[spec.key]);
    }
  },

  mounted() {
    // 组件挂载后，默认选择每个规格组的第一个选项
    this.specs.forEach(spec => {
      if (spec.values && spec.values.length > 0) {
        this.$set(this.selectedSpecs, spec.key, spec.values[0]);
        this.selectSpec(spec.key, spec.values[0]); // 触发选择以确保组件状态更新
      }
    });
  },

  methods: {
    // 提供给父组件调用的方法
    getSelectedSkuForParent() {
      return this.getSelectedSku();
    },
    // 选择规格
    selectSpec(specKey, value) {
      if (this.isOptionDisabled(specKey, value)) return;
      this.$set(this.selectedSpecs, specKey, value);
      this.$emit('change', this.getSelectedSku());
    },

    // 判断选项是否禁用
    isOptionDisabled(specKey, optionValue) {
      // 创建一个临时的选择状态，包含当前正在判断的选项
      const tempSelected = { ...this.selectedSpecs };
      tempSelected[specKey] = optionValue;

      // 检查是否存在至少一个SKU匹配这个选择组合
      return !this.skus.some(sku => {
        const spData = JSON.parse(sku.spData);
        const specMap = new Map(spData.map(spec => [spec.key, spec.value]));

        // 检查所有已选择的规格是否都匹配
        return Object.entries(tempSelected).every(([key, value]) => {
          // 如果这个规格未选择，则跳过检查
          if (!value) return true;
          // 检查这个规格值是否匹配
          return specMap.get(key) === value;
        });
      });
    },

    // 获取当前选中的SKU
    getSelectedSku() {
      if (!this.isAllSelected) return null;
      return this.skus.find(sku => {
        const spData = JSON.parse(sku.spData);
        return spData.every(spec =>
            this.selectedSpecs[spec.key] === spec.value
        );
      });
    }
  }
}
</script>
<style scoped>
/*.container {*/
/*  !*padding: 15px;*!*/
/*  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;*/
/*}*/

.sku-group {
  margin-bottom: 20px;
}

.sku-title {
  font-weight: 700;
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
}

.sku-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.sku-option {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.sku-option.selected {
  background-color: rgb(138, 182, 96);
  color: white;
  border-color: rgb(138, 182, 96);
}

.sku-option.disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
  border-color: #eee;
}

.sku-info {
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.price {
  color: rgb(138, 182, 96);
  font-size: 18px;
  font-weight: bold;
}

.stock {
  margin-left: 15px;
}
</style>